package net.sf.cldsql.sql2json.main;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Map;

import net.sf.cldsql.dj.mvc.DiServiceImpl;
import net.sf.cldsql.dj.mvc.DiContext;
import net.sf.cldsql.dj.utl.DiException;
import net.sf.cldsql.dj.utl.StrUtl;
import net.sf.cldsql.sql2json.sql.JsonBuilder;
import net.sf.cldsql.sql2json.sql.SqlRestQuery;

/**
 * Sql2JsonService
 */
public class SjServiceImpl extends DiServiceImpl implements SjService {
    
    /** @param args
    /** @return */
    public Object execute (final DiContext context, final String... args) {
        try {
            //DiContext context = (DiContext)args[0];
            Map<String,String[]> paramMap = (Map<String, String[]>) context.getParameterMap();
            log.debug("start");
            
            int baseIdx = 0;
            String method = (String)args[baseIdx + 0];
            if (method.matches("^(GET|PUT|POST|DELETE)$")) {
                baseIdx ++;
            } else {
                method = context.getMethod();
            }
            
            String table = (String)args[baseIdx + 0];
            String idValue = args.length < baseIdx + 2 ? null : (String)args[baseIdx + 1];
            
            SqlRestQuery sq = new SqlRestQuery();
            
            StrUtl sutl = new StrUtl();
            SjConf conf = container.<SjConf>get(SjConf.class);
            String idName = conf.get("table", sutl.convLJavaToSql(table).toLowerCase() + ".pk");
            idName = idName == null ? "id" : idName;

            sq.parseRequest(table, 
                    idName,
                    idValue, 
                    method, 
                    paramMap);
            StringBuilder sql = sq.buildSql();
            log.debug(new StrUtl().flattenCrLf(sql.toString()));
            PreparedStatement stmt;
            stmt = conn.getConn().prepareStatement(sql.toString());
            StringBuilder jsonBuf;
            ArrayList<String> sqlPrm = sq.getParams();
            for (int i = 0; i < sqlPrm.size(); i ++) {
                stmt.setString(i + 1, sqlPrm.get(i));
            }
            if (stmt.execute()) {
                ResultSet rset = null;
                jsonBuf = JsonBuilder.get().convResultSetToJson(rset = stmt.getResultSet());
                if (rset != null) {
                    rset.close();
                }
                stmt.close();
            } else {
                stmt.close();
                jsonBuf = new StringBuilder ("{\"status\":0}");
            }
            
            log.debug("finished with result: {}.", jsonBuf);
            return jsonBuf;
        } catch (SQLException e) {
            throw new DiException(e);
        }
    }

}
